<?php

namespace app\api\controller;

use app\data\model\DataQiyeXinxiku;
use app\data\service\UserAdminService;
use think\admin\Controller;
use think\facade\Db;

class UssoApi extends Controller
{


    public $appId = '9jlq9pooc9u4qwkbpw3ytx7gnfbugolf';
    public $appKey = 'i1cuffh6';

    public function ussoUserLogin($code){

        $code = input('code');
        if(empty($code)){
            return_error('缺少参数code');
        }


        $url = "http://ussoapi.dsj.lankao.gov.cn/api/getToken";
        $res = $this->curl_post($url, ['code' => $code,'appId'=>$this->appId]);
        $res = json_decode($res,true);


    }


    //账号授权
    public function zhanghaoCreate()
    {

        $openid = input('openid');
        $phone  = input('phone');

        if (empty($openid)) {
            return_error('获取失败：{openid}');
        }
        if (empty($phone)) {
            return_error('获取失败：{phone}');
        }
        // 判断数据库有没有这个人
        $re = Db::name('data_user')->where(['openid1' => $openid, 'deleted' => 0])->find();


        //人员存在
        if (!empty($re)) {

            if ($re['sf'] == 1) {


                $xinxiku = Db::name("data_qiye_xinxiku")->where('phone', $re['phone'])->where('deleted', 0)->find();

                if (empty($xinxiku)) {

                    //为了兼容他人身份，查询是否认证
                    $is_re_rz_count = Db::name("data_qiye_rzinfo")->where('user_id', $re['id'])->where('deleted', 0)->count();
                    if ($is_re_rz_count > 0) {
                        $re['is_rz'] = 1;
                    } else {
                        $re['is_rz'] = 0;
                    }

                } else {//信息库匹配成功

                    //获取最新的认证记录
                    $info = Db::name('data_qiye_rzinfo')->where('user_id', $re['id'])->where('deleted', 0)->find();

                    if (empty($info)) {
                        $data_qiye_rzinfo = [
                            'user_id'     => $re['id'],
                            'qymc'        => $xinxiku['qymc'],
                            'tyxydm'      => $xinxiku['tyxydm'],
                            'yyzz'        => $xinxiku['yyzz'],
                            'sbr_type'    => 1,
                            'sbr_xm'      => $xinxiku['sbr_xm'],
                            'sbr_phone'   => $xinxiku['phone'],
                            'xzbm'        => $xinxiku['xzbm'],
                            'qybq'        => $xinxiku['qybq'],
                            'create_time' => time(),
                            'qrxxk_id'    => $xinxiku['id'],
                            'qiyesf'      => 1,
                        ];

                        Db::name("data_qiye_rzinfo")->insert($data_qiye_rzinfo);

                        Db::name("data_user")->where('id', $re['id'])->update(['nickname' => $xinxiku['qymc']]);
                        $re['nickname'] = $xinxiku['qymc'];


                    } else {

                        if ($info['qrxxk_id'] != $xinxiku['id']) {//生成最新的认证

                            Db::name("data_qiye_rzinfo")->where('id', $info['id'])->where('deleted', 0)->update(['deleted' => 1]);

                            $data_qiye_rzinfo = [
                                'user_id'     => $re['id'],
                                'qymc'        => $xinxiku['qymc'],
                                'tyxydm'      => $xinxiku['tyxydm'],
                                'yyzz'        => $xinxiku['yyzz'],
                                'sbr_type'    => 1,
                                'sbr_xm'      => $xinxiku['sbr_xm'],
                                'sbr_phone'   => $xinxiku['phone'],
                                'xzbm'        => $xinxiku['xzbm'],
                                'qybq'        => $xinxiku['qybq'],
                                'create_time' => time(),
                                'qrxxk_id'    => $xinxiku['id'],
                                'qiyesf'      => 1,
                            ];

                            Db::name("data_qiye_rzinfo")->insert($data_qiye_rzinfo);

                            Db::name("data_user")->where('id', $re['id'])->update(['nickname' => $xinxiku['qymc']]);
                            $re['nickname'] = $xinxiku['qymc'];
                        }
                    }

                    $re['is_rz'] = 1;
                }
            }

            return_msg(200, 'success', $re);
        } else {

            $fwgphone = Db::name("data_fwg_phone")->where('phone', $phone)->find();
            // 插入数据库
            $array             = [];
            $array['openid1']  = $openid;
            $array['phone']    = $phone;
            $array['password'] = md5(123456);
            $array['status']   = 1;
            $array['headimg']  = sysconf('site_url') . '/upload/tx.jpg';
            $array['id']       = Db::name("data_user")->insertGetId($array);


            if (empty($fwgphone)) {

                $array['sf']       = 1;
                $array['nickname'] = '用户' . $this->generateRandomUsername();


                $xinxiku = Db::name("data_qiye_xinxiku")->where('phone', $phone)->where('deleted', 0)->find();

                if (empty($xinxiku)) {

                    $array['is_rz'] = 0;

                } else {//信息库匹配成功
                    $data_qiye_rzinfo = [
                        'user_id'     => $array['id'],
                        'qymc'        => $xinxiku['qymc'],
                        'tyxydm'      => $xinxiku['tyxydm'],
                        'yyzz'        => $xinxiku['yyzz'],
                        'sbr_type'    => $xinxiku['sbr_type'],
                        'sbr_xm'      => $xinxiku['sbr_xm'],
                        'sbr_phone'   => $xinxiku['phone'],
                        'xzbm'        => $xinxiku['xzbm'],
                        'qybq'        => $xinxiku['qybq'],
                        'create_time' => time(),
                        'qrxxk_id'    => $xinxiku['id'],
                        'qiyesf'      => 1,
                    ];

                    Db::name("data_qiye_rzinfo")->insert($data_qiye_rzinfo);

                    $array['nickname'] = $xinxiku['qymc'];
                    $array['is_rz']    = 1;
                }

            } else {
                //服务员
                $array['sf']       = 2;
                $array['nickname'] = $fwgphone['nickname'];
            }

            Db::name("data_user")->where('id', $array['id'])->update(['sf' => $array['sf'], 'nickname' => $array['nickname']]);
            return_msg(200, 'success', $array);
        }
    }


    function generateRandomUsername($length = 6)
    {
        $characters      = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $username        = '';
        $characterLength = strlen($characters);

        for ($i = 0; $i < $length; $i++) {
            $username .= $characters[rand(0, $characterLength - 1)];
        }

        return $username;
    }


    /**
     * 加密
     * @param $input
     * @param $key
     * @return string
     */
    public static function encrypt($input, $key)
    {
        $key2 = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
        $data = openssl_encrypt($input, 'aes-128-ecb', $key2, OPENSSL_RAW_DATA);
        $data = base64_encode($data);
        return $data;
    }

    /**
     * 解密
     * @param $str
     * @param $key
     * @return string
     */
    public static function decrypt($str, $key)
    {
        $key2      = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
        $encrypted = base64_decode($str);
        $data      = openssl_decrypt($encrypted, 'aes-128-ecb', $key2, OPENSSL_RAW_DATA);
        return $data;
    }


    private function curl_get($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $SSL = substr($url, 0, 8) == "https://" ? true : false;
        if ($SSL) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
        }
        $content = curl_exec($ch);
        curl_close($ch);
        return $content;
    }


    private function curl_post($url, $data)
    {
        $data  = json_encode($data);
        $headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($curl);
        curl_close($curl);

        return json_decode($output, true);
    }



    public function checkEnterpriseUser()
    {
        $enterpriseList = DataQiyeXinxiku::query()->where('status', '=', 1)
            ->where('deleted', '=', 0)->select();
        foreach ($enterpriseList as $enterprise) {
            UserAdminService::handleEnterpriseUser($enterprise->toArray());
        }
        return_msg(200, '检测成功');
    }


}
